<template>
  <div class="customer-manage">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>客户管理</h2>
      <p>管理系统中的所有客户信息</p>
    </div>

    <!-- 搜索和操作区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true" label-width="80px">
        <el-form-item label="客户姓名">
          <el-input 
            v-model="searchForm.username" 
            placeholder="请输入客户姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input 
            v-model="searchForm.pid" 
            placeholder="请输入身份证号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input 
            v-model="searchForm.telephone" 
            placeholder="请输入联系电话"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增客户
          </el-button>
          <el-button type="success" @click="handleExport" :loading="exportLoading">
            <el-icon><Download /></el-icon>
            导出CSV
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 客户列表 -->
    <el-card class="table-card">
      <el-table 
        :data="customerList" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="userid" label="用户ID" width="80" />
        <el-table-column prop="username" label="姓名" width="120" />
        <el-table-column prop="pid" label="身份证号" width="180" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            <el-tag :type="row.gender === '男' ? 'primary' : 'danger'" size="small">
              {{ row.gender }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="telephone" label="联系电话" width="130" />
        <el-table-column prop="account" label="登录账号" width="150" />
        <el-table-column prop="role" label="角色" width="80">
          <template #default="{ row }">
            <el-tag :type="row.role === 1 ? 'warning' : 'success'" size="small">
              {{ row.role === 1 ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)" :disabled="row.role === 1">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="username">
          <el-input v-model="form.username" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="pid">
          <el-input v-model="form.pid" placeholder="请输入18位身份证号" maxlength="18" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系电话" prop="telephone">
          <el-input v-model="form.telephone" placeholder="请输入11位手机号" maxlength="11" />
        </el-form-item>
        <el-form-item label="登录账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入登录账号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Edit, 
  Delete,
  Download
} from '@element-plus/icons-vue'
import { adminCustomerApi } from '@/api/customer'
import { CSVExporter, customerExportColumns } from '@/utils/csvExport'

export default {
  name: 'CustomerManage',
  components: {
    Search,
    Refresh,
    Plus,
    Edit,
    Delete,
    Download
  },
  setup() {
    const loading = ref(false)
    const submitLoading = ref(false)
    const exportLoading = ref(false)
    const dialogVisible = ref(false)
    const formRef = ref(null)
    const isEdit = ref(false)

    // 搜索表单
    const searchForm = reactive({
      username: '',
      pid: '',
      telephone: ''
    })

    // 日期范围
    const dateRange = ref([])

    // 分页
    const pagination = reactive({
      current: 1,
      size: 20,
      total: 0
    })

    // 客户列表
    const customerList = ref([])

    // 表单数据
    const form = reactive({
      userid: null,
      username: '',
      pid: '',
      gender: '男',
      telephone: '',
      account: ''
    })

    // 表单验证规则
    const rules = {
      username: [
        { required: true, message: '请输入客户姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在2到20个字符', trigger: 'blur' }
      ],
      pid: [
        { required: true, message: '请输入身份证号', trigger: 'blur' },
        { pattern: /^\d{17}[\dXx]$/, message: '请输入正确的18位身份证号', trigger: 'blur' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      telephone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
      ],
      account: [
        { required: true, message: '请输入登录账号', trigger: 'blur' },
        { min: 4, max: 20, message: '账号长度在4到20个字符', trigger: 'blur' }
      ]
    }

    // 对话框标题
    const dialogTitle = computed(() => isEdit.value ? '编辑客户' : '新增客户')

    // 获取客户列表
    const fetchCustomers = async () => {
      loading.value = true
      try {
        const queryData = {
          page: pagination.current,
          pageSize: pagination.size,
          ...searchForm
        }

        const [begin, end] = dateRange.value || []
        const response = await adminCustomerApi.pageCustomer(queryData, begin, end)
        
        if (response.code === 0) {
          customerList.value = response.data.records || []
          pagination.total = response.data.total || 0
        } else {
          ElMessage.error(response.msg || '获取客户列表失败')
        }
      } catch (error) {
        console.error('获取客户列表失败:', error)
        ElMessage.error('获取客户列表失败')
      } finally {
        loading.value = false
      }
    }

    // 搜索
    const handleSearch = () => {
      pagination.current = 1
      fetchCustomers()
    }

    // 重置
    const handleReset = () => {
      Object.assign(searchForm, {
        username: '',
        pid: '',
        telephone: ''
      })
      dateRange.value = []
      pagination.current = 1
      fetchCustomers()
    }

    // 新增
    const handleAdd = () => {
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
    }

    // 编辑
    const handleEdit = (row) => {
      isEdit.value = true
      Object.assign(form, {
        userid: row.userid,
        username: row.username,
        pid: row.pid,
        gender: row.gender,
        telephone: row.telephone,
        account: row.account
      })
      dialogVisible.value = true
    }

    // 删除
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除客户 "${row.username}" 吗？此操作不可恢复！`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await adminCustomerApi.deleteCustomer(row.userid)
        if (response.code === 0) {
          ElMessage.success('删除成功')
          fetchCustomers()
        } else {
          ElMessage.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除客户失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        submitLoading.value = true

        const api = isEdit.value ? adminCustomerApi.updateCustomer : adminCustomerApi.addCustomer
        const response = await api(form)

        if (response.code === 0) {
          ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
          dialogVisible.value = false
          fetchCustomers()
        } else {
          ElMessage.error(response.msg || '操作失败')
        }
      } catch (error) {
        console.error('提交表单失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }

    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        userid: null,
        username: '',
        pid: '',
        gender: '男',
        telephone: '',
        account: ''
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }

    // 导出CSV
    const handleExport = async () => {
      if (customerList.value.length === 0) {
        ElMessage.warning('没有数据可导出')
        return
      }

      try {
        exportLoading.value = true
        CSVExporter.exportToCSV(customerList.value, customerExportColumns, '客户管理报表')
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败: ' + error.message)
      } finally {
        exportLoading.value = false
      }
    }

    // 对话框关闭
    const handleDialogClose = () => {
      resetForm()
    }

    // 分页大小改变
    const handleSizeChange = (size) => {
      pagination.size = size
      pagination.current = 1
      fetchCustomers()
    }

    // 当前页改变
    const handleCurrentChange = (current) => {
      pagination.current = current
      fetchCustomers()
    }

    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString('zh-CN')
    }

    // 初始化
    onMounted(() => {
      fetchCustomers()
    })

    return {
      loading,
      submitLoading,
      exportLoading,
      dialogVisible,
      formRef,
      searchForm,
      dateRange,
      pagination,
      customerList,
      form,
      rules,
      dialogTitle,
      handleSearch,
      handleReset,
      handleAdd,
      handleEdit,
      handleDelete,
      handleSubmit,
      handleExport,
      handleDialogClose,
      handleSizeChange,
      handleCurrentChange,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.customer-manage {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.el-form-item {
  margin-bottom: 18px;
}
</style> 